<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */


namespace app\common\model\wework;


use app\common\model\BaseModel;
use think\facade\Log;

/**
 * 客服消息
 * Class WeworkKfMsg
 * @package app\common\model\wework
 * User: liuhongbin
 * Date: 2022-07-20 23:33
 */
class WeworkKfMsg extends WeworkBaseModel
{
    protected $type = array(
        'content' => 'json'
    );

    public function getUserAttr($value, $data)
    {
        return WeworkKfUser::where('external_userid', $data['external_userid'])->find();
    }

    /**
     * 保存消息
     * @param $msg
     * @param $next_cursor
     * @return false|void
     */
    public function saveMsgForEvent($msg, $next_cursor)
    {
        try {
            if (!$msg) {
                return false;
            }
            if ($msg['msgtype'] == "event") {
                //如果是事件消息
                $external_userid = $msg['event']['external_userid']??'';
                $open_kfid = $msg['event']['open_kfid'];
                $scene = $msg['event']['scene'] ?? '';
            } else {
                $external_userid = $msg['external_userid']??'';
                $open_kfid = $msg['open_kfid'];
                $scene = "";
            }
            $kf_user = (new WeworkKfUser())->getKfExternalUser($external_userid, $scene);
            $msg_data = array(
                'external_userid' => $external_userid,
                'open_kfid'       => $open_kfid,
                'origin'          => $msg['origin'],
                'msgtype'         => $msg['msgtype'],
                'content'         => $msg[$msg['msgtype']],
                'scene'           => $scene,
                'cursor'          => $next_cursor,
                'type'            => 0,
                'plaid'           => get_plaid()
            );
            $this->save($msg_data);
        } catch (\Exception $e) {
            Log::error(['saveMsgForEvent' => [$e->getMessage(), $e->getLine(), $e->getFile()]]);
        }
    }

    public function getLatelyIds($limit = 10)
    {
        $ids = [];
        $msgs = $this->field('id')->order('id', 'desc')->limit(0, $limit)->select();
        foreach ($msgs as $key => $value) {
            $ids[] = $value['id'];
        }
        return $ids;
    }
}
